
#include <signal.h>

#include <iostream>

#include <workflow/WFFacilities.h>
#include <workflow/WFTaskFactory.h>
#include <workflow/HttpMessage.h>
#include <workflow/HttpUtil.h>
using std::cout;
using std::endl;
using std::string;

static WFFacilities::WaitGroup waitGroup(1);

void sighandler(int num)
{
    printf(">> sig num %d is comming\n", num);
    //调用一次done方法，计数器的值减1
    waitGroup.done();
}

void httpCallback(WFHttpTask * httptask)
{
    printf("httpCallback is running\n");
    //1. 对任务的状态进行检测
    int state = httptask->get_state();
    int error = httptask->get_error();
    switch(state) {
    case WFT_STATE_SYS_ERROR:
        printf("system error: %s\n", strerror(error)); break;
    case WFT_STATE_DNS_ERROR:
        printf("dns error: %s\n", gai_strerror(error)); break;
    case WFT_STATE_SUCCESS:
        break;
    }
    if(state != WFT_STATE_SUCCESS) {
        printf("error occurs!\n");
        return;
    }
    //2. 对HttpRequest和HttpResponse进行遍历
    printf("task is ok!\n");
}

void test0()
{
    signal(SIGINT, sighandler);
    //1. 创建HttpTask
    //1.1 对于URI而言，其格式是要合法的;
    //如果不是合法的URI，任务执行时会报错
    //string url = "www.baidu.com";

    //1.2 当URI合法时，但DNS服务器无法解析的URI
    //string url = "http://wwwwwwww.baicom";
    //1.3 当URI合法且DNS服务器能够解析
    string url = "http://www.baidu.com";
    auto httpTask = WFTaskFactory::create_http_task(url, 1, 1, httpCallback);
    //2. 设置任务的属性
    
    //3. 启动HttpTask任务，交给框架调度执行
    httpTask->start();

    //当调用wait方法会阻塞当前线程
    waitGroup.wait();
    cout << "test0 exit" << endl;
}


int main()
{
    test0();
    return 0;
}

